<?php

App::uses('AppController', 'Controller');

class OrdersController extends AppController {
    
    public $uses = array('Order', 'CustomerType', 'Brand', 'BrandModel', 'OrderDeleted');
    
    public $title = 'Nalozi';
    
    public $paginate = array(
        'limit'  => self::ITEMS_PER_PAGE,
        'order'  => 'Order.datum_izdavanja DESC',
        'fields' => array('Order.*', 'BrandModel.name', 'Brand.name'),
        'recursive' => -1,
        'joins'  => array(
            array(
                'table'      => 'brand_models',
                'alias'      => 'BrandModel',
                'type'       => 'LEFT',
                'conditions' => 'Order.brand_model_id=BrandModel.id'
            ),
            array(
                'table'      => 'brands',
                'alias'      => 'Brand',
                'type'       => 'LEFT',
                'conditions' => 'BrandModel.brand_id=Brand.id'
            )
        )
    );
    
    public function index() {
        $data = array_merge($this->params->query, $this->data);
        
        $keyword    = trim( @$data['keyword'] );
        $nezavrseni = @$data['nezavrseni'];
        $nepreuzeti = @$data['nepreuzeti'];
        
        $conditions = array(
            'AND' => array( 'Order.store_id' => $this->getStore('id')
        ));
        if (! empty($keyword)) {
            $SearchFields = array(
                "Order.id"                => "string",
                "Order.datum_izdavanja"   => "date",
                "Order.musterija_ime"     => "string",
                "Order.musterija_telefon" => "string",
                "BrandModel.name"         => "string",
                "Brand.name"              => "string",
                "Order.imei"              => "string",
                "Order.problem"           => "string",
                "Order.datum_popravke"    => "date",
                "Order.datum_preuzimanja" => "date",
                "Order.napomena"          => "string"
            );
            $conditions['OR'] = array();
            foreach ($SearchFields as $name=>$type){
                switch ($type){
                    case "date":
                        $conditions['OR']["{$name} LIKE"] = $keyword . "%";
                        break;
                    default:
                        $conditions['OR']["{$name} LIKE"] = "%". $keyword . "%";
                        break;
                }
            }
        }
        if ($nezavrseni) {
            $conditions['AND']['Order.datum_popravke'] = null;
        }
        if ($nepreuzeti) {
            $conditions['AND']['Order.datum_preuzimanja'] = null;
        }
        $orders = $this->paginate('Order', $conditions);
        
        $this->set(compact('keyword', 'nezavrseni', 'nepreuzeti', 'orders'));
    }
    
    protected function setCommonData() {
        $this->set('customerTypes', $this->CustomerType->find('list', array(
            'fields' => array('id', 'tip'),
            'order'  => 'tip'
        )));
        $this->set('flagOptions', array(1=>'DA', 0=>'NE'));
    }
    public function create() {
        $this->set('data', $this->Order->create());
        $this->setCommonData();
        $this->render('form');
    }
    
    public function edit($id) {
        if (! $data = $this->Order->find('first', array(
            'conditions' => array('Order.id' => $id),
            'recursive'  => 2
        ))) {
            $this->redirect('index');
        }
        
        $this->set('isPrint', $this->Session->read('Order.isPrint'));
        $this->Session->write('Order.isPrint', false);

        $this->set(compact('data'));
        $this->setCommonData();
        $this->render('form');
    }
    
    public function save() {
        $data = $this->data;
        if (empty($data)) {
            $this->redirect('index');
        }

        // is print?
        $isPrint = $this->params->params['named']['print'];
        if ($isPrint) {
            $this->Session->write('Order.isPrint', true);
        }
        
        // locate Brand
        $data['Order']['brand_id']       = $this->Brand->field('id', array(
                                               'name'=>$data['Order']['brand_id']
                                           ));
        // locate Brand Model
        $data['Order']['brand_model_id'] = $this->BrandModel->field('id', array(
                                               'brand_id' => $data['Order']['brand_id'],
                                               'name'     => $data['Order']['brand_model_id']
                                           ));
                                           
        $this->Order->create();
        $this->Order->set($data);
        if(! $this->Order->validates()) {
            $this->set('data', $data);
            $this->setCommonData();
            $this->flashError('Uneti podaci nisu validni.');
            $this->render('form');
        } else if(! $this->Order->save($data)) {
            $this->set('data', $data);
            $this->setCommonData();
            $this->flashError('Čuvanje nije uspelo.');
            $this->render('form');
        } else {
            $this->flashOk('Sačuvano.');
            $this->redirect("/orders/edit/" . $this->Order->id);
        }
    }
    
    public function delete($id) {
        if($id>0 && $order = $this->Order->findById($id)) {
            
            if ($this->OrderDeleted->save($order['Order'])) {            
                if ($this->Order->delete($id)) {
                    $this->flashOk('Nalog #'.$id.' je obrisan.');
                } else {
                    $this->flashError('Brisanje nije uspelo.');
                    return $this->redirect('/orders/edit/'.$id);
                }
            }
        }
        
        $this->redirect('index');
    }
    
    public function aprint($id) {
        $this->layout = 'print';
        
        $store       = $this->getStore();
        list($order) = $this->Order->findAllById($id, '*', null, 1, 1, 2);
        
        $this->set(compact('order', 'store'));
    }
}